<?php

namespace app\admin\controller;

use app\admin\service\BaseService;
use support\Request;
use support\Response;
use support\View;
use app\admin\model\admin\Admin;
use app\admin\model\admin\AdminConfig;

class BaseController
{
    protected $request;

    protected $service;

    protected $siteInfo;
    protected $siteArr;

    protected $adminInfo;

    protected int $version;

    public function __construct()
    {
        //$this->request = Request();

        //赋值当前菜单
        if (method_exists($this, '_infoModule')) {
            $this->assign('infoModule', $this->_infoModule());
        }

        $this->getSiteInfo();

        $this->getAdminInfo();

        $this->version = $this->systemVersion();
        $this->assign('version', $this->version);
        $versionText = $this->version == 1 ? '单页' : ($this->version == 2 ? '伪框架' : '框架');
        $this->assign('versionText', $versionText);

        //令牌
        $this->assign('tokenName', '__admin__');

        $this->act_log();
    }

    protected function act_log(): void
    {
        $request = request();

        $method = $request->method();
        $path = $request->path();
        $uri = $request->uri();
        $url = $request->url();
        $params = $request->queryString();
        $ip = $request->getRemoteIp();

        $log = 'IP：' . $ip . ' [' . $method . '] ';
        $log .= '操作方法：' . $path . ' ';
        $log .= '参数：' . json_encode($params, JSON_UNESCAPED_UNICODE);
        set_log('app_log', $log);
    }

    protected function getSiteInfo(): void
    {
        $info = [];
        $arr = [];
        $modelConfig = new AdminConfig();
        $list = $modelConfig->select();
        foreach ($list as $key => $value) {
            $info[$value['name']] = $value['data'];
            $arr[] = [
                $value['name'] => $value['data'],
                'text' => $value['note']
            ];
        }
        $this->siteInfo = $info;
        $this->siteArr = $arr;
        $this->assign('siteInfo', $info);
        $this->assign('siteArr', $arr);
    }

    protected function getAdminInfo(): void
    {
        try {
            if (session('username')) {
                $username = session('username');

                $modelAdmin = new Admin();
                $adminInfo = $modelAdmin->where('username', '=', $username)->findOrEmpty();
                if ($adminInfo->isEmpty()) {
                    throw new \Exception('请重新登录');
                }

                $this->adminInfo = $adminInfo;
                $this->assign('adminInfo', $adminInfo);
            }
        } catch (\Throwable $e) {
            redirect('/admin/login/index');
        }
    }

    /**
     * @param int $set_v
     * @return int
     */
    protected function systemVersion(int $set_v = 0): int
    {
        /**
         * 1 单页版
         * 2 伪框架版
         * 3 框架版
         */
        $version = [1, 2, 3];
        $v = 1;
        $file = "./version.txt";

        if ($set_v == 0) {
            if (file_exists($file)) {
                //文件存在 读取
                $handle = fopen($file, "r");
                $v = fread($handle, "1");
                fclose($handle);

                //验证
                if (in_array($v, $version)) {
                    return $v;
                }
            }
        } else {
            if (in_array($set_v, $version)) {
                $v = $set_v;
            }
        }

        //文件不存在 创建 或 版本错误 修改
        $file = fopen($file, "w");
        fwrite($file, $v);
        fclose($file);

        return $v;
    }

    protected function assign($param, $data = []): void
    {
        view::assign($param, $data);
    }

    protected function fetch($view): Response
    {
        return view($view);
    }

    /**
     * 中断反馈信息
     * @access  protected
     * @param string $m 信息字符
     * @param int $c 状态值 400前台关闭 401Ajax请求未登陆 303网址请求未登录 -1Ajax请求返回业务错误
     * @param array $d 数组信息
     * @param array $h 发送的Header信息
     * @return mixed
     */
    protected final function exitMsg($m, $c = 0, $d = [], $h = [])
    {
        $t = null;
        if ($c == 400 || $c == 303) {
            $d['msg'] = $m;
            $t = 'app/exception/v_msg.tpl';
        }
        throw new \app\exception\ExitMsg($m, $t, $c, $d, $h);
    }

    /**
     * 获取分页配置
     * @param bool $isPage
     * @return array
     */
    protected function getPageValue(bool $isPage = true): array
    {
        $page = $limit = 0;
        if ($isPage) {
            $page = input('page', 0);
            $limit = input('limit', 20);
        }

        $search = [];
        $input = input();
        if(!empty($input)){
            foreach ($input as $key => $value) {
                if (in_array($key, ['do','page', 'limit'])) {
                    continue;
                }
                $search[$key] = $value;
            }
        }

        $where = [];
        if (!empty($search)) {
            if (!empty($search['fields'])) {
                !empty($search['kw']) && $where[] = [$search['fields'], 'like', '%' . $search['kw'] . '%'];
                unset($search['fields']);
                unset($search['kw']);
            }
            foreach ($search as $key => $value) {
                if (str_contains($key, 'id') || str_contains($key, 'time') || in_array($key, ['status'])) {
                    if(str_contains($key, 'time') && str_contains($value, ' - ')){
                        $timeAry = explode(' - ', $value);
                        $where[] = [$key, 'between', [strtotime($timeAry[0]), strtotime($timeAry[1])]];
                    }else{
                        !empty($value) && $where[] = [$key, '=', $value];
                    }
                }else{
                    !empty($value) && $where[] = [$key, 'like', '%' . $value . '%'];
                }
            }
        }

        return [(int)$page, (int)$limit, $where];
    }

    protected function checkField(array $files): Response|array
    {
        if (empty($files)) {
            return [];
        }

        $data = [];
        foreach ($files as $key => $value) {
            $param = explode('|', $value);
            if (empty($param)) {
                continue;
            }
            $input = input();
            if (count($param) == 1) {
                if (!isset($input[$value]) || empty($input[$value])) {
                    $this->exitMsg('参数 ' . $value . ' 未设置', -1);
                }
                $data[$value] = is_array($input[$value]) ? $input[$value] : filterWords($input[$value]);
            } else {
                $data[$param[0]] = input($param[0], $param[1]);
//                if (!isset($input[$param[0]]) || empty($input[$param[0]])) {
//                    if ($input[$param[0]] == 0){
//                        $input[$param[0]] = 0;
//                    }else{
//                        $data[$param[0]] = ($param[1] == '' || $param[1] == 'null' || $param[1] == null) ? '' : $param[1];
//                    }
//                } else {
//                    $data[$param[0]] = is_array($input[$param[0]]) ? $input[$param[0]] : filterWords($input[$param[0]]);
//                }
            }
        }
        return $data;
    }

}